//
//  HMUIRefreshControl.swift
//  sinaWeiBo
//
//  Created by weixq on 15/8/9.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit
// 下拉刷新的便宜量，超出之后，翻转动画
private let kRefreshPullOffset: CGFloat = -60

// 下拉刷新控件，集成在tableView controller
class HMUIRefreshControl: UIRefreshControl {
    
    // MARK: - 重写刷新方法
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
    }
    

    // 构造函数
    // 下拉表格y值越来越小，上啦y值越来越大，
    // 拖拽到一定程度会进入自动刷新状态
    
 
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
//        print(frame)
        
        // 判断是否开始刷新，如果开始属性播放动画
        if refreshing {
            refreshView.startLoading()
        }
        
        // 如果y大于o，直接返回
        if frame.origin.y > 0 {
            return
        }
        
        if frame.origin.y < kRefreshPullOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = true
        }else if frame.origin.y > kRefreshPullOffset && refreshView.rotateFlag{
            refreshView.rotateFlag = false
        }
        
    }
    
    // MARK: - 构造函数
    override init() {
        super.init()
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    deinit{
        self.removeObserver(self, forKeyPath: "frame")
    }

    private func setupUI() {
        
        // KVO 监听 frame 属性变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
        
        // 添加控件
        addSubview(refreshView)
        
        // 隐藏菊花
        tintColor = UIColor.clearColor()
        
        // 设置自动布局   从xib加载的时候，可以直接取得真实大小
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    
    }
    
    // MARK: - 懒加载控件
    
    private lazy var refreshView : HMRefreshView = HMRefreshView.refreshView()
    
}

// 下拉刷新视图，负责显示和动画
class HMRefreshView : UIView {
    
    // 选择标记
     var rotateFlag = false {
        didSet{
            rotateTipIcon()
        }
    }
    
    @IBOutlet weak var tipIcon: UIImageView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var loadingIcon: UIImageView!
    
    
    // 从xib加载视图
    class func refreshView() -> HMRefreshView {
    
        return NSBundle.mainBundle().loadNibNamed("HMRefreshView", owner: nil, options: nil).last as! HMRefreshView
    }
    
    // 提示图片的旋转
    private func rotateTipIcon() {
        //
        let angle = rotateFlag ? CGFloat(M_PI-0.01) : CGFloat(M_PI+0.01)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            // 这个狗日的方法很很有脾气，第二个参数为旋转的度数，如果旋转大于180度，它会走路径比较近的
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        }
    }
    
    // 开始加载动画
    private func startLoading() {
        
        if loadingIcon.layer.animationForKey("loadingAnim") != nil{
            return
        }
        
        // 1. 隐藏提示视图
        tipView.hidden = true
        
        // 2. 定义动画
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        
        anim.toValue = 2 * M_PI
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.5
        
        // 3. 添加动画
        loadingIcon.layer.addAnimation(anim, forKey: "loadingAnim")
    }
    
    // 停止加载动画
    private func stopLoading() {
        tipView.hidden = false
        loadingIcon.layer.removeAllAnimations()
    }
    
}